const PROMISE_STATUS_PENDING = "PROMISE_STATUS_PENDING";
const PROMISE_STATUS_FULFTLLED = "PROMISE_STATUS_FULFTLLED";
const PROMISE_STATUS_REJECTED = "PROMISE_STATUS_REJECTED";

class Mypromise {
  status = PROMISE_STATUS_PENDING;
  value;
  reason;
  onfulfilledfns = [];
  onrejectedfns = [];
  constructor(executor) {
    const resolve = (value) => {
      process.nextTick(() => {
        if (this.status === PROMISE_STATUS_PENDING) {
          this.status = PROMISE_STATUS_FULFTLLED;
          this.value = value;
          this.onfulfilledfns.forEach((fn) => {
            fn(this.value);
          });
        }
      });
    };

    const reject = (reason) => {
      process.nextTick(() => {
        if (this.status === PROMISE_STATUS_PENDING) {
          this.status = PROMISE_STATUS_REJECTED;
          this.reason = reason;
          this.onrejectedfns.forEach((fn) => {
            fn(this.reason);
          });
        }
      });
    };
    executor(resolve, reject);
  }

  then = (onfulfilled, onrejected) => {


    if (this.status == PROMISE_STATUS_FULFTLLED) {
      onfulfilled(this.value);
      return;
    }

    if (this.status == PROMISE_STATUS_REJECTED) {
      onrejected(this.reason);
      return;
    }

    this.onfulfilledfns.push(onfulfilled);
    this.onrejectedfns.push(onrejected);
  };
}

var promise = new Mypromise((resolve, reject) => {
  resolve("123");
  reject("error");
});

promise.then(
  (res) => {
    console.log("res1", res);
  },
  (err) => {
    console.log("err1", err);
  }
);

promise.then(
  (res) => {
    console.log("res2", res);
  },
  (err) => {
    console.log("err2", err);
  }
);

setTimeout(() => {
  promise.then(
    (res) => {
      console.log("res3", res);
    },
    (err) => {
      console.log("err3", err);
    }
  );
}, 1000);
